package net.suncaper.mvc.common.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.serializer.SimpleDateFormatSerializer;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

public class JSONUtil {
    private static SerializeConfig config;
    
    static {
        // 配置FastJSON日期序列化格式
        config = new SerializeConfig();
        config.put(Date.class, new SimpleDateFormatSerializer("yyyy-MM-dd HH:mm:ss"));
    }
    
    public static void printByJSON(HttpServletResponse response, Object obj) {
        String jsonStr = "";
        if (obj != null && !"".equals(obj)) {
            // 使用配置好的config进行序列化，确保日期被格式化为字符串
            jsonStr = JSON.toJSONString(obj, config, SerializerFeature.WriteDateUseDateFormat);
        }
        PrintWriter out = null;
        try {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("text/json;charset=UTF-8");
            out = response.getWriter();
            out.print(jsonStr);
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                out.close();
            }
        }
    }
}
